<template>
  <div class="travel-master-page">
    <el-container style="height: 100vh;">
      <!-- 侧边栏 -->
      <el-aside width="300px" class="sidebar">
        <div class="sidebar-header">
          <el-button type="primary" @click="goHome" icon="el-icon-back" circle></el-button>
          <h3>AI旅游大师</h3>
          <el-button type="success" @click="createNewChat" icon="el-icon-plus" circle></el-button>
        </div>
        
        <div class="chat-list">
          <div class="chat-list-header">
            <span>会话列表</span>
          </div>
          <div class="chat-sessions">
            <div 
              v-for="session in chatSessions" 
              :key="session.id"
              :class="['chat-session-item', { active: currentChatId === session.id }]"
              @click="switchChat(session.id)"
            >
              <div class="session-info">
                <div class="session-title">{{ session.title || '新会话' }}</div>
                <div class="session-time">{{ formatTime(session.createTime) }}</div>
              </div>
              <el-button 
                type="text" 
                icon="el-icon-delete" 
                @click.stop="deleteChat(session.id)"
                class="delete-btn"
              ></el-button>
            </div>
          </div>
        </div>
      </el-aside>

      <!-- 主聊天区域 -->
      <el-main class="chat-main">
        <div class="chat-container">
          <!-- 聊天消息区域 -->
          <div class="messages-container" ref="messagesContainer">
            <div v-if="messages.length === 0" class="welcome-message">
              <div class="welcome-content">
                <i class="el-icon-chat-dot-round"></i>
                <h3>欢迎使用AI旅游大师</h3>
                <p>我是您的专属旅游顾问，可以为您提供：</p>
                <ul>
                  <li>旅游目的地推荐</li>
                  <li>行程规划建议</li>
                  <li>酒店和景点信息</li>
                  <li>旅游注意事项</li>
                </ul>
                <p>请告诉我您的旅游需求，我会为您提供专业的建议！</p>
              </div>
            </div>
            
            <div 
              v-for="(message, index) in messages" 
              :key="index"
              :class="['message-item', message.role]"
            >
              <div class="message-content">
                <div v-if="message.role === 'user'" class="user-message">
                  {{ message.content }}
                </div>
                <div v-else class="assistant-message">
                  <div class="assistant-avatar">
                    <i class="el-icon-user-solid"></i>
                  </div>
                  <div class="assistant-content">
                    <div class="message-text" v-html="formatMessage(message.content)"></div>
                    <div v-if="message.loading" class="typing-indicator">
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-container">
            <div class="input-box">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="3"
                placeholder="请输入您的旅游问题..."
                @keydown.ctrl.enter="sendMessage"
                :disabled="isLoading"
                maxlength="500"
                show-word-limit
              ></el-input>
              <div class="input-actions">
                <el-button 
                  type="primary" 
                  @click="sendMessage" 
                  :loading="isLoading"
                  :disabled="!inputMessage.trim()"
                >
                  发送 (Ctrl+Enter)
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { getSSEURL } from '@/config/apiConfig'

export default {
  name: 'TravelMaster',
  data() {
    return {
      inputMessage: '',
      messages: [],
      isLoading: false,
      currentChatId: '',
      chatSessions: [],
      eventSource: null
    }
  },
  created() {
    this.createNewChat()
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close()
    }
  },
  methods: {
    goHome() {
      this.$router.push('/')
    },
    
    async createNewChat() {
      try {
        const response = await this.$http.get('/ai/chat/new')
        const newChatId = response.data
        
        const newSession = {
          id: newChatId,
          title: '新会话',
          createTime: new Date(),
          messages: []
        }
        
        this.chatSessions.unshift(newSession)
        this.currentChatId = newChatId
        this.messages = []
        
        this.$message.success('新会话已创建')
      } catch (error) {
        this.$message.error('创建新会话失败：' + error.message)
      }
    },
    
    switchChat(chatId) {
      if (this.eventSource) {
        this.eventSource.close()
        this.eventSource = null
      }
      
      this.currentChatId = chatId
      const session = this.chatSessions.find(s => s.id === chatId)
      if (session) {
        this.messages = session.messages || []
      }
    },
    
    deleteChat(chatId) {
      this.$confirm('确定要删除这个会话吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.chatSessions = this.chatSessions.filter(s => s.id !== chatId)
        if (this.currentChatId === chatId) {
          if (this.chatSessions.length > 0) {
            this.switchChat(this.chatSessions[0].id)
          } else {
            this.createNewChat()
          }
        }
        this.$message.success('会话已删除')
      }).catch(() => {})
    },
    
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      const userMessage = {
        role: 'user',
        content: this.inputMessage.trim(),
        timestamp: new Date()
      }
      
      this.messages.push(userMessage)
      
      // 添加助手消息占位符
      const assistantMessage = {
        role: 'assistant',
        content: '',
        loading: true,
        timestamp: new Date()
      }
      this.messages.push(assistantMessage)
      
      const messageToSend = this.inputMessage.trim()
      this.inputMessage = ''
      this.isLoading = true
      
      this.scrollToBottom()
      
      try {
        await this.sendSSEMessage(messageToSend, assistantMessage)
      } catch (error) {
        this.$message.error('发送消息失败：' + error.message)
        assistantMessage.content = '抱歉，服务暂时不可用，请稍后再试。'
        assistantMessage.loading = false
      } finally {
        this.isLoading = false
        this.updateSessionMessages()
      }
    },
    
    sendSSEMessage(message, assistantMessage) {
      return new Promise((resolve) => {
        // 关闭之前的连接
        if (this.eventSource) {
          this.eventSource.close()
          this.eventSource = null
        }
        
        // 使用统一的SSE URL配置
        const url = getSSEURL(`/ai/chat/travel/sse/emitter?message=${encodeURIComponent(message)}&chatId=${this.currentChatId}`)
        
        this.eventSource = new EventSource(url)
        
        this.eventSource.onmessage = (event) => {
          try {
            console.log('SSE原始数据:', event.data)
            
            // 检查是否为结束信号
            if (event.data === '[DONE]') {
              console.log('SSE数据流结束')
              assistantMessage.loading = false
              if (this.eventSource) {
                this.eventSource.close()
                this.eventSource = null
              }
              resolve()
              return
            }
            
            // 处理正常数据
            let data = event.data
            
            // 如果数据不为空且不是空白字符
            if (data && data.trim()) {
              // 直接添加到消息内容中
              assistantMessage.content += data
              this.scrollToBottom()
              this.$forceUpdate()
            }
          } catch (error) {
            console.error('解析SSE数据失败:', error, 'Original data:', event.data)
          }
        }
        
        this.eventSource.onerror = (error) => {
          console.error('SSE连接错误:', error)
          console.log('EventSource readyState:', this.eventSource ? this.eventSource.readyState : 'null')
          
          // 如果连接正在建立中，直接关闭并退出
          if (this.eventSource && this.eventSource.readyState === EventSource.CONNECTING) {
            console.log('SSE连接正在建立中，直接关闭')
            this.eventSource.close()
            this.eventSource = null
            assistantMessage.loading = false
            resolve()
            return
          }
          
          // 检查是否为正常关闭
          if (this.eventSource && this.eventSource.readyState === EventSource.CLOSED) {
            console.log('SSE连接已正常关闭')
            // 如果没有收到任何内容，提示用户连接已关闭
            if (!assistantMessage.content.trim()) {
              assistantMessage.content = '连接异常关闭';
            }
            assistantMessage.loading = false
            resolve()
            return
          }
          
          // 其他错误情况：关闭连接，同时提示用户
          if (this.eventSource) {
            this.eventSource.close()
            this.eventSource = null
          }
          
          // 显示错误信息给用户
          const errorMessage = (error && error.message) ? error.message : '连接异常，请稍后重试';
          if (!assistantMessage.content.trim()) {
            assistantMessage.content = '抱歉，' + errorMessage;
          }
          
          assistantMessage.loading = false
          resolve()
        }
        
        this.eventSource.onopen = () => {
          console.log('SSE连接已建立')
        }
      })
    },
    
    updateSessionMessages() {
      const session = this.chatSessions.find(s => s.id === this.currentChatId)
      if (session) {
        session.messages = [...this.messages]
        // 更新会话标题（使用第一条用户消息的前20个字符）
        if (session.title === '新会话' && this.messages.length > 0) {
          const firstUserMessage = this.messages.find(m => m.role === 'user')
          if (firstUserMessage) {
            session.title = firstUserMessage.content.substring(0, 20) + (firstUserMessage.content.length > 20 ? '...' : '')
          }
        }
      }
    },
    
    formatMessage(content) {
      if (!content) return ''
      return content.replace(/\n/g, '<br>')
    },
    
    formatTime(date) {
      if (!date) return ''
      const now = new Date()
      const diff = now - date
      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      return date.toLocaleDateString()
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }
  }
}
</script>

<style scoped>
.travel-master-page {
  height: 100vh;
  background: #f5f5f5;
}

.sidebar {
  background: #fff;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.chat-list {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-list-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e8e8e8;
  font-weight: 600;
  color: #666;
}

.chat-sessions {
  flex: 1;
  overflow-y: auto;
}

.chat-session-item {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-session-item:hover {
  background-color: #f8f8f8;
}

.chat-session-item.active {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.session-info {
  flex: 1;
}

.session-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-time {
  font-size: 12px;
  color: #999;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s;
}

.chat-session-item:hover .delete-btn {
  opacity: 1;
}

.chat-main {
  background: #fff;
  padding: 0;
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.welcome-message {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.welcome-content i {
  font-size: 48px;
  color: #1890ff;
  margin-bottom: 20px;
}

.welcome-content h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.welcome-content ul {
  text-align: left;
  display: inline-block;
  margin: 20px 0;
}

.welcome-content li {
  margin: 8px 0;
}

.message-item {
  margin-bottom: 20px;
}

.message-item.user {
  text-align: right;
}

.user-message {
  display: inline-block;
  max-width: 70%;
  padding: 12px 16px;
  background: #1890ff;
  color: white;
  border-radius: 18px;
  word-wrap: break-word;
}

.assistant-message {
  display: flex;
  align-items: flex-start;
  max-width: 85%;
}

.assistant-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #666;
}

.assistant-content {
  flex: 1;
}

.message-text {
  padding: 12px 16px;
  background: #f8f8f8;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.5;
}

.typing-indicator {
  display: flex;
  padding: 12px 16px;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.input-container {
  border-top: 1px solid #e8e8e8;
  padding: 20px;
  background: #fff;
}

.input-box {
  max-width: 800px;
  margin: 0 auto;
}

.input-actions {
  margin-top: 10px;
  text-align: right;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.chat-sessions::-webkit-scrollbar {
  width: 4px;
}

.chat-sessions::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-sessions::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}
</style>